@extends('layouts.default')

@section('title', '用户管理')

@push('scripts')
    <script>
        var totalNUm = 0;
        var table;
        var form;
        var laypage;
        var layer;
        var filters = '';
        var addLayer;
        var editLayer;
        var id = '';
        var tree;
        var util;
        var laytpl;
        var rolelist;
        var tableData;
        var curr_page = 1;
        var element;
        var upload;

        $(function(){
            layui.use(['table','form','element','laypage','tree','util','upload','laytpl'], function() {
                table = layui.table;
                element = layui.element;
                form = layui.form;
                laypage = layui.laypage;
                layer = layui.layer;
                tree = layui.tree;
                util = layui.util;
                upload = layui.upload,
                laytpl = layui.laytpl;

                renderSelect();
                getList(1);

                // 监控switch
                form.on('switch(status)', function(obj){
                    var index  = obj.othis.parents('tr').attr("data-index");
                    var id = tableData[index].id;
                    var status = obj.elem.checked?1:2;
                    setUserStatus({"id":id,"status":status},function (res) {
                        if(res.code == 1) {
                            layer.msg(res.msg, {
                                time: 2000,
                                icon: 6
                            });
                            var index  = obj.othis.parents('tr').attr("data-index");
                            if (status == '1'){
                                tableData[index].active_flag = '1';
                            }else{
                                tableData[index].active_flag = '0';
                            }
                        } else {
                            layer.msg(res.msg, {
                                time: 2000,
                                icon: 5
                            });
                            location.reload();
                        }
                    })

                });
                table.on('toolbar(tablelsit)', function(obj){
                    var checkStatus = table.checkStatus(obj.config.id);
                    var ids = [];
                    var data = checkStatus.data;
                    for(var k=0; k<data.length;k++){
                        ids.push(data[k]['id'])

                    }
                    var para = {"id" : ids, "status": '1'};
                    switch(obj.event){
                        case 'effectData':
                            para.status = '1';
                            setUserStatus(para,function (res) {
                                if(res.code == 1) {
                                    layer.msg(res.msg, {time: 2000, icon: 6});
                                    getList(curr_page);
                                } else {
                                    layer.msg(res.msg, {time: 2000, icon: 5});
                                }
                            });
                            break;
                        case 'banData':
                            para.status = '2';
                            setUserStatus(para,function (res) {
                                if(res.code == 1) {
                                    layer.msg(res.msg, {time: 2000, icon: 6});
                                    getList(curr_page);
                                } else {
                                    layer.msg(res.msg, {time: 2000, icon: 5});
                                }
                            });
                            break;
                        case 'updateIdCard':
                            //上传excel文件
                            layer.open({
                                title:'同步教师身份证号数据',
                                type: 1,
                                area: ['500px', '300px'],
                                content: $('#import-idinfo'), //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
                            });
                            break;
                    }
                });

                // 设置用户角色提交
                form.on('submit(setRole)', function(data) {
                    var data = data.field;
                    var param = {
                        "id" : data.user_id,
                    };
                    delete data['user_id']
                    var arr = [];
                    for (var item in data){
                        arr.push(data[item]);
                    }
                    param.roleid = arr;
                    setUserRole(param,function (res) {
                        if(res.code == 1) {
                            $('#Dialoge').hide();
                            layer.msg(res.msg, {
                                time: 2000,
                                icon: 6
                            });
                            getList(curr_page);
                        } else {
                            $('#Dialoge').hide();
                            layer.msg(res.msg, {
                                time: 2000,
                                icon: 5
                            });
                        }
                        layer.close(editLayer);
                    })

                    return false;
                });

                // 搜索查询
                form.on('submit(selectBtn)', function(data) {
                    var param = data.field;
                    filters = param
                    getList(1)
                })

                table.on('tool(tablelsit)', function(obj) {
                    var data = obj.data;
                    id = data.id;

                    if(obj.event === 'setRole') { //设置角色弹窗
                        layer.ready(function() {
                            var index = layer.load(2);
                            editLayer = layer.open({
                                type: 1,
                                title: "设置角色",
                                content: $('#Dialoge'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
                                area: ['700px', '500px'],
                                cancel: function() {
                                    //右上角关闭回调
                                    $('#Dialoge').hide();
                                    $('#editForm')[0].reset()
                                    //return false 开启该代码可禁止点击该按钮关闭
                                }
                            });
                            layer.close(index);
                        });
                        //获取编辑的值
                        var roleids = data.roleid;
                        var roleids = ','+roleids+',';
                        $('#rolelist').empty();
                        for(var i=0; i<rolelist.length;i++) {
                            if(roleids.indexOf(','+rolelist[i].id+',') != -1 ){
                                console.log(','+rolelist[i].id+',');
                                $('#rolelist').append('<div class="layui-input-inline"><input type="checkbox" checked name="roles[]" title="'+rolelist[i].rolename+'" value="'+rolelist[i].id+'"></div>');
                            }else{
                                $('#rolelist').append('<div class="layui-input-inline"><input type="checkbox" name="roles[]" title="'+rolelist[i].rolename+'" value="'+rolelist[i].id+'"></div>');
                            }
                        }
                        $('#userid').val(id);
                        form.render('checkbox');

                    }
                });

                //上传excel文件
                upload.render({
                    elem: '#btn-upload'
                    ,url: "{{route('systems.users.updateInfo')}}" //改成您自己的上传接口
                    ,accept: 'file'
                    ,size: '20480'
                    ,exts: 'xlsx|xls'
                    ,headers: {"X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr('content')}
                    ,done: function(res){
                        layer.closeAll('loading');
                        if(res.code == 1){
                            $('#import-idinfo').find('.msg-span').text(res.data.msg);
                            if(res.data.is_fail == '1'){
                                layer.msg(res.msg,{icon: 6,time: 2000},function(){
                                    window.location.reload();
                                });
                            }else{
                                $('#import-idinfo').find('.but-1').hide();
                                $('#import-idinfo').find('.but-2').show().attr('file-name', res.data.file_name);
                            }
                        }else{
                            $('#import-idinfo').find('.msg-span').text('');
                            layer.msg(res.msg, {icon: 5,shift : 6});
                        }
                    }
                    ,before: function(obj){ //obj参数包含的信息，跟 choose回调完全一致，可参见上文。
                        let classId = $("select[name='class_id']").val();
                        
                        this.data = {
                            class_id: classId
                        }
                        $('#import-idinfo').find('.msg-span').text('正在导入...');
                        layer.load(); //上传loading
                    }
                    ,error: function(index, upload){
                        layer.closeAll('loading');
                    }
                });

                //下载错误文件
                $('#import-idinfo').find('.but-2').click(function(){
                    window.location.href = "{{ route('download.FileDownloadDel') }}"+'?filename=用户信息同步失败的错误信息.xlsx&file_url=' + $(this).attr('file-name');
                });
            });
            $('#resetBtn').on('click',function () {
                window.location.reload();
            });
        });

        // 获取页面数据
        function getList(page) {
            if (filters == ''){
                filters = {}
            }
            var para = {
                "page": page,
                "filters": filters
            };
            getUserList(para, function(res){
                if(res.code == 1) {
                    if(totalNUm != res.total) {
                        totalNUm = res.total;
                        renderPageBar(page)
                    }

                    table.render({
                        data: res.data,
                        elem: '#tablelsit',
                        toolbar: '#toolbarDemo',
                        defaultToolbar: [],
                        limit: 10,
                        cols: [[
                            // {type: 'checkbox', fixed: 'left'}, 
                            {field: 'user_name',title: '姓名',width: '18%',align: 'center'},
                            {field: 'user_id',title: '用户名',width: '18%',align: 'center'},
                            {field: 'rolename',title: '角色',width: '25%',align: 'center'},
                            // {title: '状态',width: '10%',align: 'center',templet: '#barDemo'},
                            {title: '操作',align: 'center',toolbar: '#opDemo'}
                        ]],
                        id:"tableIns",
                        done: function(res, curr, count) {
                            setBtnPermission();
                            tableData = table.cache.tableIns;
                        },
                        page: false,
                        loading: true
                    });
                } else {
                    layer.msg(res.msg, {
                        time: 2000,
                        icon: 5
                    });
                }
                form.render('select');
            });

        }

        // 渲染页面
        function renderPageBar(page) {
            laypage.render({
                elem: 'pageBar',
                count: totalNUm, //数据总数，从服务端得到
                curr: page,
                limit: 10,
                first: '第一页',
                last: '最后一页',
                layout: ['count', 'prev', 'page', 'next', 'skip'],
                jump: function(obj, first) {
                    //首次不执行
                    if(!first) {
                        layer.closeAll();
                        curr_page = obj.curr;
                        getList(obj.curr)
                    }
                }
            });
        }

        function renderSelect() {
            getAllRoles(null,function (res) {
                if(res.code === 1){
                    rolelist = res.data;
                    if(rolelist.length>0){
                        for(var i=0; i<rolelist.length;i++) {
                            $('[data-role="rolelist"]').append('<option value="'+rolelist[i].id+'">'+rolelist[i].rolename+'</option>');
                            // $('#rolelist').append('<div class="layui-input-inline"><input type="checkbox" name="roles[]" title="'+rolelist[i].rolename+'" value="'+rolelist[i].id+'"></div>');
                        }
                    }
                }
            })
        }
    </script>
@endpush

@section('content')
<style>
    .layui-tree-set{
        width: 30%;
    }
    .layui-form-label{
        /* text-align: left;
        width: 100px; */
    }
    .layui-form-checkbox span {
        width: 85px;
    }
    #rolelist > div.layui-input-inline {
        padding: 10px 10px;
        display: table-cell;
    }
    #rolelist{
        margin-left: 0;
    }
</style>

<div class="layui-card">
    <div class="layui-card-body">
        <div class="layui-row">
            <div class="layui-col-md12" >                            
                <div class="layui-form-item">
                    <form class="layui-form" action="">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">姓名:</label>
                            <div class="layui-input-inline" >
                                <input type="text" name="name" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">用户名:</label>
                            <div class="layui-input-inline" >
                                <input type="text" name="username" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <!-- <div class="layui-inline">
                            <label class="layui-form-label">状态:</label>
                            <div class="layui-input-inline" >
                                <select name="status" lay-filter="statuslist"  data-role="statuslist" >
                                    <option value="">全部</option>
                                    <option value="2">禁用</option>
                                    <option value="1">启用</option>
                                </select>
                            </div>
                        </div> -->
                        
                        <div class="layui-inline">
                            <label class="layui-form-label">角色:</label>
                            <div class="layui-input-inline" >
                                <select name="role" lay-filter="rolelist"  data-role="rolelist" >
                                    <option value="">全部</option>
                                </select>
                            </div>
                        </div>
                        <button type="button" lay-submit lay-filter="selectBtn" class="pear-btn pear-btn-primary ">查询</button>
                        <button type="button" id="resetBtn" class="pear-btn">重置</button>
                    </div>
                    
             
                    
                    <input id="group_id" type="hidden" name="group_id">
                    </form>                 
                </div>            
            </div>             
        </div>
    </div>
</div>
<div class="layui-card" style="padding:10px;" >
    <script type="text/html" id="toolbarDemo">
        <div class="layui-btn-container">
            <!-- <button class="layui-btn layui-btn-normal" lay-event="effectData"  btnPermission="161">启用</button>
            <button style="margin-left:10px;" class="layui-btn layui-btn-normal" lay-event="banData" btnPermission="160">禁用</button> -->
            <button style="margin-left:10px;" class="layui-btn layui-btn-normal" lay-event="updateIdCard">同步用户信息</button>
        </div>
    </script>        
                
    <table class="layui-hide" id="tablelsit" lay-filter="tablelsit" lay-data="{id: 'tablelsit'}"></table>
    <div class="pagebarbox" style="text-align: end"><div id="pageBar" class="pagebar"></div></div>

    <script type="text/html" id="barDemo">
        @{{#  if(d.active_flag == '1'){ }}
        <span style="color: forestgreen">启用</span>
        @{{# }else{ }}
        <span style="color: red">禁用</span>
        @{{# } }}
    </script>
    <script type="text/html" id="opDemo">
        <a class="layui-btn layui-btn-primary layui-border-blue layui-btn-xs" lay-event="setRole" btnPermission="162">设置角色</a>
    </script>
</div>
    

<!--设置角色弹窗-->
<div id="Dialoge" class="dialogue" style="display: none;padding: 20px;text-align: center;">
    <form class="layui-form" action="" id="editForm" lay-filter="editForm">
        <div class="layui-form-item">
            <div class="layui-input-block" id="rolelist"></div>
        </div>
        <input type="hidden" name="user_id" id="userid" value="">
        <div style="text-align: center; clear: both;">
            <button class="layui-btn  layui-btn-normal" lay-submit lay-filter="setRole" style="padding: 0 50px; margin-top: 20px;">提交</button>
        </div>
    </form>
</div>

<!-- 同步教师身份证号数据 -->
<div id="import-idinfo" style="display:none; padding:30px 20px;">
    <form id="importIdInfoForm" class="layui-form" action="">
        <div class="layui-row">
            <button type="button" class="pear-btn pear-btn-primary pear-btn-sm cursor" id="btn-upload" >选择上传文件</button>
            <span class="msg-span" style="color: #999;"></span>
        </div>
        <div class="layui-row" style="margin-top:20px;">
            <button type="button" class="layui-btn layui-btn-disabled layui-btn-sm but-1" >下载同步失败的数据文件</button>
            <button type="button" class="layui-btn layui-btn-danger layui-btn-sm but-2" style="display:none;margin-left:0px;" file-name="">下载同步失败的数据文件</button>
        </div>
    </form>
</div>
@endsection